class Book < ActiveRecord::Base
  belongs_to :category
  has_many :borrow_items
  before_destroy :ensure_not_referenced_by_any_borrow_item
  
  validates :name, :presence => true, :uniqueness => true
  validates_numericality_of :numbers, :greater_than_or_equal_to => 1, :only_integer => true
  validates_numericality_of :numbers_to_borrow, :less_than_or_equal_to => :numbers, :greater_than_or_equal_to => 0, :only_integer => true
  
  def self.search(search)
    if search
      find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
    else
      find(:all)
    end
  end
  
  def self.search_by_author(search)
    if search
      find(:all, :conditions => ['author LIKE ?', "%#{search}%"])
    else
      find(:all)
    end
  end
  
  def self.search_by_date(search)
    if search
      find(:all, :conditions => ['created_at LIKE ?', "%#{search}%"])
    else
      find(:all)
    end
  end
  
  def self.search_hot_book()
    where("created_at >= :start_date", {:start_date => Date.current.beginning_of_week()})
  end
  
  def self.search_hot_book_2(number)
        Book.order("view")
        Book.limit("#{number}")
  end
  
  def self.search_new_book_in_day()
        Book.order("name")
        Book.where("created_at = :cond",{:cond=>"%#{DateTime.current}%"})
  end
  
  def self.search_new_book_in_week()
      Book.order("name")
      Book.where("created_at >= :start_date", {:start_date => DateTime.current.beginning_of_week()})
  end
  
    def self.search_new_book_in_month()
      Book.order("name")
      Book.where("created_at >= :start_date", {:start_date => DateTime.current.beginning_of_month()})
  end
  
  
  private
  # ensure that there are no line items referencing this product
  def ensure_not_referenced_by_any_borrow_item
    if borrow_items.empty?
      return true
    else
      errors.add(:base, 'Borrow Items present')
      return false
    end
  end
end
